<template>
  <el-row>
    <div class="topnav">
      <!-- 论坛logo-->
      <div class="logo">
        <img
          src="https://lyking90.oss-cn-shenzhen.aliyuncs.com/boringman/logo.png"
          alt="图标"
          style="width:40px;height:40px;margin-right:8px;"
        />
        无聊人论坛
      </div>

      <!--导航栏-->
      <el-menu
        :default-active="activeIndex2"
        class="el-menu-demo"
        mode="horizontal"
        @select="handleSelect"
        background-color="#199ED8"
        text-color="#fff"
        active-text-color="#ffd04b"
      >
        <el-menu-item index="1"
          ><router-link to="/">首页</router-link>
        </el-menu-item>
        <el-menu-item index="2">
          <span @click="drawer = true">关于我们</span>
        </el-menu-item>
        <el-menu-item index="3">
          <span @click="open">赞赏支持</span>
        </el-menu-item>
      </el-menu>

      <!-- 抽屉-->
      <el-drawer title="我是标题" :visible.sync="drawer" :with-header="false">
        <h2 class="mt">团队介绍</h2>
        <h3 class="mt">项目：无聊人论坛</h3>
        <h3 class="mt">组名：素质教育之漏网之鱼</h3>
        <h3 class="mt" style="margin:5px;line-height:35px;">
          介绍：基于Vue+SpringBoot的前后端分离项目，实现论坛的帖子发表，浏览，点赞收藏，用户管理，帖子管理等主要功能。
        </h3>
        <div class="team">
          <div class="mt mb tcolor">前端开发</div>
          <div
            style="width:75px;border:1px solid#eee;padding:2px; display: inline-block; margin: 3px;"
          >
            <img
              src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1791011043,2222909746&fm=26&gp=0.jpg"
              alt="img"
              style="width:75px;height:75px;"
            />
            <div style="text-align: center;">苏基明</div>
          </div>
          <div
            style="width:75px;border:1px solid#eee;padding:2px; display: inline-block; margin: 3px;"
          >
            <img
              src="https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1489346502,1355781396&fm=26&gp=0.jpg"
              alt="img"
              style="width:75px;height:75px;"
            />
            <div style="text-align: center;">黄柏乐</div>
          </div>
          <div
            style="width:75px;border:1px solid#eee;padding:2px; display: inline-block; margin: 3px;"
          >
            <img
              src="https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1515606012,4282800830&fm=26&gp=0.jpg"
              alt="img"
              style="width:75px;height:75px;"
            />
            <div style="text-align: center;">宋俊武</div>
          </div>
        </div>

        <div class="team">
          <div class="mt mb tcolor">后端开发</div>
          <div
            style="width:75px;border:1px solid#eee;padding:2px; display: inline-block; margin: 3px;"
          >
            <img
              src="https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3777546133,924987311&fm=26&gp=0.jpg"
              alt="img"
              style="width:75px;height:75px;"
            />
            <div style="text-align: center;">何龙灿</div>
          </div>
          <div
            style="width:75px;border:1px solid#eee;padding:2px; display: inline-block; margin: 3px;"
          >
            <img
              src="https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2438727878,3798230596&fm=26&gp=0.jpg"
              alt="img"
              style="width:75px;height:75px;"
            />
            <div style="text-align: center;">黎嘉聪</div>
          </div>
          <div
            style="width:75px;border:1px solid#eee;padding:2px; display: inline-block; margin: 3px;"
          >
            <img
              src="https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3195225144,378902488&fm=26&gp=0.jpg"
              alt="img"
              style="width:75px;height:75px;"
            />
            <div style="text-align: center;">杨智达</div>
          </div>
        </div>
      </el-drawer>

      <!-- 搜索框-->
      <div class="search">
        <el-input
          placeholder="搜索帖子"
          prefix-icon="el-icon-search"
          @keyup.enter.native="searchPosts"
          v-model="title"
        ></el-input>
      </div>

      <div class="edit" v-if="$store.state.userInfo != null">
        <el-button type="primary" icon="el-icon-edit" @click="toPublish"
          >发表帖子</el-button
        >
      </div>

      <!--登录注册-->
      <div class="login-btn" v-if="$store.state.userInfo == null">
        <el-button type="text" @click="dialogFormVisible = true"
          >登录·注册</el-button
        >
      </div>
      <!--用户头像信息-->
      <div class="user" v-if="$store.state.userInfo != null">
        <el-row class="block-col-2">
          <el-col :span="12">
            <el-dropdown @command="handleCommand">
              <img
                :src="$store.state.userInfo.avatar"
                alt
                class="el-dropdown-link"
              />
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item icon="el-icon-user-solid" command="myInfo"
                  >个人中心</el-dropdown-item
                >
                <el-dropdown-item icon="el-icon-s-promotion" command="logout"
                  >退出</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
        </el-row>

        <div class="username">{{ $store.state.userInfo.username }}</div>
      </div>

      <el-dialog
        :title="isRegister ? '注册' : '登录'"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
        width="320px"
      >
        <!-- 登录表单 -->
        <!--button按钮绑定enter事件会执行两次，故把keyup绑定在了密码输入框-->

        <el-form
          :model="loginForm"
          status-icon
          :rules="loginFormRules"
          ref="loginRef"
          v-if="!isRegister"
        >
          <el-form-item key="username" prop="username">
            <el-input
              type="text"
              placeholder="请输入用户名"
              v-model="loginForm.username"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item key="loginPassword" prop="password">
            <el-input
              type="password"
              show-password
              placeholder="请输入密码"
              v-model="loginForm.password"
              clearable
              @keyup.enter.native="toLogin"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              class="submit-btn"
              type="primary"
              @click="toLogin"
              :loading="loBtnLoading"
              >登录</el-button
            >
          </el-form-item>
          <el-row type="flex" justify="space-between">
            <el-col :span="10">
              没有账号?
              <el-button type="text" @click="changeShowRegister"
                >去注册</el-button
              >
            </el-col>
            <el-col :span="6">
              <el-button type="text" @click="toForget">忘记密码?</el-button>
            </el-col>
          </el-row>
        </el-form>

        <!-- 注册表单 -->
        <el-form
          :model="registerForm"
          v-else
          status-icon
          :rules="registerFormRules"
          clearable
          ref="registerRef"
        >
          <el-form-item key="registerUsername" prop="username">
            <el-input
              type="text"
              placeholder="请输入用户名"
              v-model="registerForm.username"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item key="registerPassword" prop="password">
            <el-input
              placeholder="请输入密码"
              type="password"
              show-password
              v-model="registerForm.password"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item prop="repassword">
            <el-input
              placeholder="请确认密码"
              type="password"
              show-password
              v-model="registerForm.repassword"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item prop="email">
            <el-input
              placeholder="请输入您的邮箱"
              type="text"
              v-model="registerForm.email"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item prop="phone">
            <el-input
              placeholder="请输入您的手机号码"
              type="text"
              v-model="registerForm.phone"
              clearable
            ></el-input>
          </el-form-item>

          <el-form-item prop="phoneCode" v-show="isRightPhone">
            <el-col :span="12">
              <el-input
                placeholder="手机验证码"
                type="text"
                v-model="registerForm.phoneCode"
                clearable
              ></el-input>
            </el-col>
            <el-col :span="10" :offset="2">
              <el-button
                type="primary"
                :disabled="isSendEmail"
                @click="sendPhoneCode"
                >{{
                  !isSendPhone ? "发送验证码" : "还剩" + phoneSecond + "s"
                }}</el-button
              >
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-button
              class="submit-btn"
              type="primary"
              @click="toRegister"
              :loading="reBtnLoading"
              >注册</el-button
            >
          </el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="10">
              <el-button type="text" @click="changeShowRegister"
                >已有账号，去登录</el-button
              >
            </el-col>
          </el-row>
        </el-form>
      </el-dialog>
    </div>
  </el-row>
</template>

<script>
// import Login from '@/components/f-login'
export default {
  data() {
    // 邮箱验证规则
    let checkEmail = (rule, value, callback) => {
      if (!value.trim()) {
        rule.field === "loginEmail" && (this.isRightEmail = false);
        callback(new Error("请输入邮箱地址"));
      }
      // eslint-disable-next-line no-useless-escape
      let myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
      if (!myreg.test(value)) {
        this.isRightEmail = false;
        callback(new Error("输入邮箱不符合规则"));
      } else {
        this.isRightEmail = true;
        callback();
      }
    };

    //手机号码验证规则
    let checkPhone = (rule, value, callback) => {
      let myphone = /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/;
      if (!myphone.test(value)) {
        this.isRightPhone = false;
        callback(new Error("请输入正确的手机号码"));
      } else {
        this.isRightPhone = true;
        callback();
      }
    };

    let checkRepass = (rule, value, callback) => {
      if (value !== this.registerForm.password) {
        callback(new Error("两次输入密码不相同"));
      } else {
        callback();
      }
    };

    let checkUsername = [
      { required: true, message: "请输入用户名", trigger: "blur" },
      { min: 3, max: 8, message: "长度在 3 到 8 个字符", trigger: "blur" },
    ];
    let checkPassword = [
      { required: true, message: "请输入密码", trigger: "blur" },
      { min: 3, max: 16, message: "长度在 3 到 16 个字符", trigger: "blur" },
    ];

    return {
      // 对话框当前状态
      dialogFormVisible: false,

      // 是否点击注册
      isRegister: false,
      // 邮箱验证是否正确
      isRightEmail: false,
      //手机输入是否正确
      isRightPhone: false,
      // 是否发送过手机验证码
      isSendMail: false,
      isSendPhone: false,
      // 重新发送手机验证码按钮时间
      phoneSecond: 60,
      timer: null,

      //注册按钮加载
      reBtnLoading: false,
      // 登录按钮加载
      loBtnLoading: false,

      //登录表单数据
      loginForm: {
        username: "",
        password: "",
      },

      // 登录表单的校验对象
      loginFormRules: {
        username: checkUsername,
        password: checkPassword,
      },

      //注册表单数据
      registerForm: {
        username: "",
        password: "",
        repassword: "",
        email: "",
        phone: "",
        phoneCode: "",
      },

      //注册表单的校验对象
      registerFormRules: {
        username: checkUsername,
        password: checkPassword,
        phone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkPhone, trigger: "blur" },
        ],
        repassword: [
          { required: true, message: "请输入确认密码", trigger: "blur" },
          { validator: checkRepass, trigger: "blur" },
        ],
        email: [{ validator: checkEmail, trigger: "blur" }],
        phoneCode: [
          { required: true, message: "请输入手机验证码", trigger: "blur" },
        ],
      },

      // 表单字体的宽度
      formLabelWidth: "120px",
      activeIndex2: "1",
      // 搜索词
      title: "",
      drawer: false,
      // 页码
      currentPage: 1,
      // 帖子列表
      postsList: [],
      // 数据总数
      total: 0,
      // 一页10条
      pageSize: 10,
    };
  },
  components: {
    // Login,
  },
  methods: {
    handleSelect(key, keyPath) {
      console.log(key, keyPath);
    },

    //点击去注册
    changeShowRegister() {
      this.isRegister = !this.isRegister;
    },

    //点击发表
    toPublish() {
      this.$router.push("/publish");
    },
    //下拉菜单的个人中心，退出登录点击事件
    handleCommand(command) {
      // this.$message('click on item ' + command);
      if (command === "logout") {
        this.logout();
      } else if (command === "myInfo") {
        this.myInfo();
      } else {
        return;
      }
    },

    //退出登录
    logout() {
      this.$axios.post("/logout").then((res) => {
        this.$store.commit("REMOVE_INFO");
        this.$message.success("退出成功");
        //跳转回主页
        this.$router.push("/Home");
      });
    },

    //进入个人中心
    myInfo() {
      this.$message.success("欢迎！");
      this.$router.push("/personal");
    },

    //关闭对话框
    loginDiaClose() {
      // if (this.dialogFormVisible) {
      //   this.$refs.loginRef && this.$refs.loginRef.resetFields();
      //   this.$refs.registerRef && this.$refs.registerRef.resetFields();
      //   this.$store.commit("changeDialogFormVisible");
      // }
      this.dialogFormVisible = false;
    },
    //点击登录
    toLogin() {
      this.$refs.loginRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("请填写正确的信息");
        }
        this.loBtnLoading = true;

        //登录判断
        var _this = this;
        this.$axios
          .post(
            "/login?username=" +
              this.loginForm.username +
              "&password=" +
              this.loginForm.password
          )
          .then((res) => {
            if (res.data.code === 200) {
              console.log(res);
              const userinfo = res.data.data;
              console.log(userinfo);
              //把用户信息存入全局
              _this.$store.commit("SET_ROLE", userinfo.role);
              _this.$store.commit("SET_USERINFO", userinfo);
              this.$message({
                message: "登录成功",
                type: "success",
              });
              //登录成功，关闭登录对话框
              this.loginDiaClose();
            } else {
              //登录失败
              this.$message({
                message: res.data.msg,
                type: "error",
              });
            }
          });

        this.loBtnLoading = false;
      });
    },
    //注册
    toRegister() {
      this.$refs.registerRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("请填写正确的信息");
        }
        // this.reBtnLoading = true;

        const _this = this;
        this.$axios
          .post(
            "isCorrect?phone=" +
              this.registerForm.phone +
              "&verificationCode=" +
              this.registerForm.phoneCode
          )
          .then((res) => {
            console.log("验证码正确？");
            console.log(res);
            if (res.data.code !== 200) {
              this.$message.success("验证码不正确");
              return;
            }
            this.addUser();
          });
      });
    },
    //验证码成功添加用户信息
    addUser() {
      const user = this.registerForm;
      this.$axios.post("/forum/user/save", user).then((res) => {
        // this.reBtnLoading = false;
        console.log(res);
        if (res.data.code !== 200) {
          this.$message.success("注册失败，请重新尝试！");
        }
        this.$message.success("注册成功,欢迎进入无聊人论坛");

        this.loginDiaClose();
      });
    },
    // 发送验证码
    async sendPhoneCode() {
      const _this = this;
      this.$axios.post("/send/" + this.registerForm.phone).then((res) => {
        console.log(res);
        console.log(res.data);
        if (res.data.code !== 200) {
          return;
        }
        this.$message.success("发送成功，5分钟内有效，请注意查收");
        this.countDown();
      });
    },
    // 验证码倒计时
    countDown() {
      this.isSendPhone = true;
      this.timer = setInterval(() => {
        if (this.phoneSecond <= 0) {
          this.isSendPhone = false;
          this.phoneSecond = 60;
          clearInterval(this.timer);
        }
        this.phoneSecond--;
      }, 1000);
    },

    //todo-忘记密码
    toForget() {
      // const { href } = this.$router.resolve("/forget");
      // window.open(href, "_blank");
    },

    // 模态框方法
    open() {
      this.$alert(
        "<h3>打赏包辣条吧~</h3><img src='https://lyking90.oss-cn-shenzhen.aliyuncs.com/boringman/supportme.jpg' width='200px' >",
        "赞赏支持",
        {
          dangerouslyUseHTMLString: true,
          center: true,
        }
      );
    },

    //搜索帖子
    searchPosts: function() {
      console.log(this.title);
      console.log(this.currentPage);
      this.$emit("toSearch", this.title);
    },
  },
};
</script>

<style lang="less">
:root {
  font-size: 16px;
}
a {
  text-decoration: none;
}
.login-btn {
  text-align: center;
  line-height: 68px;
  transition: 1s ease-in-out;
  // flex: 2;
  .el-button--text {
    font-size: 16px;
    color: white;
  }

  &:hover {
    transform: scale(1.3);
  }
}
.submit-btn {
  width: 100%;
}
.el-dialog__body {
  border: 1px solid #e6e6e6;
}

div.team {
  height: 200px;
  width: 90%;
  border: 2px solid #eee;
  margin: auto;
  margin-top: 30px;
  /* box-shadow: 5px 3px 5px #77797a; */
}
.mt {
  margin-top: 10px;
}
.mb {
  margin-bottom: 20px;
}
.tcolor {
  color: #0984e3;
  font-style: bold;
  font-size: large;
}
div.topnav {
  display: flex;
  justify-content: space-around;
  background-color: #199ed8;
  text-align: center;
  & .logo {
    color: white;
    font-size: 1.5rem;
    display: flex;
    justify-content: center;
    align-items: center;

    &:hover {
      transform: rotateY(360deg);
      transition: 1.5s;
      color: #222f3e;
      cursor: pointer;
    }
  }

  & .user {
    display: flex;
    align-items: center;
  }
  & .user img {
    border-radius: 50%;
    height: 45px;
  }

  div.username {
    color: white;
    padding-left: 10px;
    /* text-shadow: 5px 5px 8px #222f3e; */
  }

  div.search {
    display: flex;
    align-items: center;
  }

  div.edit {
    display: flex;
    align-items: center;
  }
}
</style>
